import Taro, { Component, getBluetoothDevices } from '@tarojs/taro'
import { View, Image, Text, ScrollView } from '@tarojs/components'
import { AtActivityIndicator, AtToast } from 'taro-ui'
import PullDown from './components/index'
import Dialog from '../../components/login'
import { post } from '../../service/api'
import './index.scss'

class Design extends Component {
  constructor() {
    super(...arguments)
    this.state = {
      msg: "",
      info: [],
      pageNo: 1,
      total: 0,
      params: {},
      login: false,
      loading: true,
      isShowToast: false,
      isShowDialog: false,
    }
  }
  config = {
    navigationBarTitleText: '装修设计',
  }
  pop(msg) {
    this.setState({
      isShowToast: true,
      msg: msg
    }, () => {
      setTimeout(() => {
        this.setState({
          isShowToast: false
        })
      }, 1500)
    })
  }
  async favoriteAdd(id, e) {
    e.stopPropagation();
    const { info } = this.state, { data } = await post('favorite/addupdate', {
      targetId: id,
      crudType: "add"
    })
    if (data.code == 0) {
      this.setState({
        info: info.map(item => {
          if (item._id == id) {
            item.isFavorite = "0"
          }
          return item
        }
        )
      })
      this.pop('收藏成功')
    } else {
      this.setState({
        isShowDialog: true
      })
    }
  }
  async favoriteDel(id, e) {
    e.stopPropagation();
    let arr = [];
    arr.push(id)
    const { info } = this.state, { data } = await post('favorite/addupdate', {
      targetId: JSON.stringify(arr),
      crudType: "delete"
    })
    if (data.code == 0) {
      this.setState({
        info: info.map(item => {
          if (item._id == id) {
            item.isFavorite = "1"
          }
          return item
        }
        )
      })
      this.pop('取消收藏')
    } else {
      this.setState({
        isShowDialog: true
      })
    }
  }
  handleDialog() {
    this.setState({
      isShowDialog: false
    })
  }
  async getCompany() {
    const { pageNo, info } = this.state,
      id = this.$router.params.id,
      lpId = this.$router.params.lpId,
      params = {
        cId: id ? id : "",
        lpId: lpId ? lpId : "",
        pageNo: pageNo,
        ...this.state.params
      },
      { data } = await post('anli/findPageList', params)
    if (data.code == 0) {
      this.setState({
        info: info.concat(data.rows),
        total: data.total,
        loading: true
      }, () => {
        if (data.rows.length >= data.total) {
          this.setState({
            loading: false
          })
        }
      })
      if (id) {
        Taro.setNavigationBarTitle({
          title: data.rows[0].companyName
        })
      }
      if (lpId) {
        Taro.setNavigationBarTitle({
          title: data.rows[0].lpName
        })
      }
    }
  }

  onScrollToLower() {
    let { info, pageNo, total } = this.state;
    if (info.length < total) {
      pageNo += 1;
      this.setState({
        pageNo,
      }, () => {
        this.getCompany()
      })
    } else {
      this.setState({
        loading: false
      })
    }
  }
  onGetInfo(e) {
    this.setState({
      pageNo: 1,
      info: [],
      params: e
    }, () => {
      this.getCompany()
    })
  }
  async cardFind() {
    const { data } = await post('vipCard/find');
    if (data.code == 0) {
      this.setState({
        login: true
      })
    }
  }
  toProgram(item) {
    let { login } = this.state, number = Taro.getStorageSync('number');
    number ? Taro.setStorageSync('number', ++number) : Taro.setStorageSync('number', 1)
    if (login) {
      Taro.navigateTo({ url: `/pages/program/index?id=${item._id}` })
    } else {
      if (number > 20) {
        this.setState({
          isShowDialog: true
        })
        return;
      }
      Taro.navigateTo({ url: `/pages/program/index?id=${item._id}` })
    }
  }
  componentDidMount() {
    this.cardFind()
    this.getCompany()
  }
  render() {
    const { isShowDialog, info, loading, total, isShowToast } = this.state;
    return (
      <View className='h-design'>
        <View className="h-top"><PullDown onGetInfo={this.onGetInfo.bind(this)} /></View>
        <View className="design">
          <ScrollView className="d-list" scrollY scrollWithAnimation lowerThreshold='10'
            onScrollToLower={this.onScrollToLower.bind(this)}>
            {info.map((item) => {
              return (
                <View className="d-item" key={item._id} onClick={this.toProgram.bind(this, item)}>
                  <View className="design-bg">
                    <Image className="design-logo" src={item.logo} />
                    <Image className={item.isFavorite ? (item.isFavorite == '1' ? "favorite" : "none") : "favorite"} onClick={this.favoriteAdd.bind(this, item._id)} src={require("../../asset/imgs/favorite.png")} />
                    <Image className={item.isFavorite == '0' ? "favorite" : "none"} onClick={this.favoriteDel.bind(this, item._id)} src={require("../../asset/imgs/favorite2.png")} />
                    <View className="qj">360°全景</View>
                    <View className="plot-name">{item.lpName}</View>
                  </View>
                  <View className="item-title">{item.title}</View>
                  <View className="item-case">
                    <View className="i-area">
                      <Image className="icon" src={require("../../asset/imgs/mj.png")} />{item.acre}㎡
                    <Image className="icon left" src={require("../../asset/imgs/ys.png")} />{item.sum / 10000}万
                  </View>
                    <View className="i-num">NO:{item.itemNumber}</View>
                  </View>
                  <View className="item-name">{item.companyName}</View>
                </View>
              )
            })}

            {
              loading && <View className="loading">
                <AtActivityIndicator mode='normal' color="#FFAE34" content='加载中...'></AtActivityIndicator>
              </View>
            }
            {
              !total && <View className="none-box">
                <Image className="img" src={require('../../asset/imgs/none.png')} />
                <View className="hint">暂时没有相应信息</View>
              </View>
            }
          </ScrollView>
        </View>
        {isShowDialog && <Dialog title="成为欢乐家会员海量方案等你来选" onHandleDialog={this.handleDialog} />}
        <AtToast
          isOpened={isShowToast}
          text={msg}
          duration={2000}
        ></AtToast>
      </View>
    )
  }
}

export default Design
